<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="crud-group">
      <!-- 搜索 -->
      <el-input
        v-model="query.taskCode"
        clearable
        placeholder="请输入导出批次"
      />
      <el-input
        v-model="query.taskName"
        clearable
        placeholder="请输入任务名"
      />
      <el-select
        v-model="query.taskStatus"
        placeholder="请选择导出状态"
        clearable
      >
        <el-option
          v-for="item in taskStatusList"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-select
        v-model="query.isDelDataFile"
        placeholder="文件删除状态"
        clearable
      >
        <el-option
          v-for="item in isDelDataFileStringList"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <rrOperation :crud="crud" />
      <el-button
        type="primary"
        icon="el-icon-tickets"
        @click="showFilterTableList"
      >过滤表清单
      </el-button>
      <el-button
        type="success"
        icon="el-icon-search"
        @click="toShowAllDetail()"
      >导出列表
      </el-button>
    </div>
    <div style="margin-bottom: 10px">
      <el-button
        type="primary"
        icon="el-icon-plus"
        @click="createTaskDialogVisible = true"
      >创建任务</el-button>
      <div style="display: inline-block;margin-left: 10px">
        <el-button
          :disabled="dynamicBatchDelFileButton(crud.selections) || isFtpDeleting"
          type="danger"
          :icon="isFtpDeleting ? 'el-icon-loading':'el-icon-delete'"
          @click="batchDelFtpDataFile(crud.selections)"
        >删除FTP文件
        </el-button>
      </div>
      <div style="display: inline-block;margin-left: 10px">
        <el-button
          :disabled="crud.selections.length === 0 || isTaskDeleting"
          type="danger"
          :icon="isTaskDeleting ? 'el-icon-loading':'el-icon-delete'"
          @click="toDelete(crud.selections)"
        >删除任务
        </el-button>
      </div>
      <div style="display: inline-block;margin-left: 10px">
        <el-button
          :disabled="dynamicSuspendButton(crud.selections)"
          type="danger"
          icon="el-icon-video-pause"
          @click="suspend(crud.selections)"
        >暂停
        </el-button>
      </div>
      <div style="display: inline-block;margin-left: 10px">
        <el-button
          :disabled="dynamicRestartButton(crud.selections)"
          type="primary"
          icon="el-icon-video-play"
          @click="restart(crud.selections)"
        >继续
        </el-button>
      </div>
      <div style="display: inline-block;margin-left: 10px">
        <el-button
          :disabled="dynamicAbolishButton(crud.selections)"
          type="danger"
          icon="el-icon-switch-button"
          @click="abolish(crud.selections)"
        >中止
        </el-button>
      </div>
      <div style="display: inline-block;margin-left: 10px">
        <create-task-dialog
          v-if="createTaskDialogVisible"
          :dialog-visible="createTaskDialogVisible"
          :on-close="onClose"
        />
      </div>
      <div style="display: inline-block;float: right;margin-left: 10px">
        <div style="display: inline-block;margin-left: 10px">
          {{ ftpTakeUp }} {{ takeUpUnit }} / {{ ftpTotal }} TB
        </div>
        <div style="display: inline-block;margin-left: 10px">
          <el-progress
            class="no-wrap-progress"
            style="width: 200px"
            :percentage="this.ftpPercent"
            :color="customColor"
          />
        </div>
        <div style="display: inline-block;margin-left: 10px">
          <el-tooltip
            :content="this.lastRefreshTime"
            placement="top"
          >
            <el-button
              type="primary"
              :icon="isRefreshing ? 'el-icon-loading':'el-icon-refresh'"
              :disabled="isRefreshing"
              @click="countFtpTakeUp"
            >刷新
            </el-button>
          </el-tooltip>
        </div>
      </div>
    </div>
    <!--表格渲染-->
    <el-table
      ref="table"
      v-loading="crud.loading"
      :data="crud.data"
      border
      @select="crud.selectChange"
      @select-all="crud.selectAllChange"
      @selection-change="crud.selectionChangeHandler"
    >
      <el-table-column
        type="selection"
        width="40"
      />
      <el-table-column
        fixed
        label="导出批次"
        prop="taskCode"
        width="130"
      />
      <el-table-column
        fixed
        label="任务名称"
        prop="taskName"
        width="180"
      />
      <el-table-column
        label="导出模式"
        prop="exportModelString"
        width="400"
      />
      <el-table-column
        label="表名称"
        prop="libraryTableName"
        width="100px"
      >
        <template slot-scope="scope">
          <a
            style="color: dodgerblue"
            @click="libraryTableopen(scope.row.taskCode)"
          >查看表名称</a>
        </template>
      </el-table-column>
      <el-table-column
        label="导出路径"
        prop="filePath"
        width="220"
      />
      <el-table-column
        label="文件大小"
        prop="fileSizeString"
        width="100"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.fileSizeString === null"> 计算中 </span>
          <span v-if="scope.row.fileSizeString !== null"> {{ scope.row.fileSizeString }} </span>
        </template>
      </el-table-column>
      <el-table-column
        label="导出状态"
        prop="taskStatusName"
      />
      <el-table-column
        label="导出进度"
        width="210px"
      >
        <template slot-scope="scope">
          <el-tag type="info">总数：{{ scope.row.exportTotal }}</el-tag>
          <el-tag
            type="success"
            style="margin: 0px 5px"
          >成功: {{ scope.row.exportSuccess }}</el-tag>
          <el-tag type="danger">失败: {{ scope.row.exportFail }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column
        label="FTP文件"
        prop="isDelDataFileString"
      />
      <el-table-column
        label="开始时间"
        prop="startTimeString"
        width="180"
      />
      <el-table-column
        label="结束时间"
        prop="endTimeString"
        width="180"
      />
      <el-table-column
        label="耗时"
        prop="timeConsuming"
        width="180"
      />
      <el-table-column
        fixed="right"
        label="操作"
        width="200"
      >
        <template slot-scope="scope">
          <el-button
            :disabled="scope.row.isDelDataFile == 'Y'"
            type="text"
            @click="delFtpDataFile(scope.row.id)"
          >删除FTP文件</el-button>
          <el-button
            type="text"
            :disabled="scope.row.taskStatus !== 'incomplete'"
            @click="continueRun(scope.row.id)"
          >
            重新加载
          </el-button>
          <el-button
            type="text"
            @click="toShowDetail(scope.row.taskCode)"
          >查看</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style=" float: right;">
      <!--分页组件-->
      <pagination />
    </div>
    <details-dialog
      v-if="detailsDialogVisible"
      :task-code="crunTaskCode"
      :dialog-visible="detailsDialogVisible"
      :on-close="() => { detailsDialogVisible = false}"
    />
    <dev-all-details-dialog
      v-if="alldetailsDialogVisible"
      :dialog-visible="alldetailsDialogVisible"
      :on-close="() => { alldetailsDialogVisible = false}"
    />
    <el-dialog
      :close-on-click-modal="false"
      :before-close="() => { showFilterTableListVisible = false}"
      :visible.sync="showFilterTableListVisible"
      title="过滤表清单"
      width="1000px"
      append-to-body
    >
      <data-transfer-filter-table v-if="showFilterTableListVisible" transfer-type="DEV" />
    </el-dialog>
    <el-dialog
      width="30%"
      title="表名称详情"
      :visible="libraryTableNameFlag"
      append-to-body
      @close="libraryTableclose"
    >
      <div>
        <codemirror
          ref="codemirror"
          :value="libraryTableName"
          :editor-height="200"
          :read-only="true"
        />
      </div>
      <span
        slot="footer"
        class="dialog-footer"
        style="text-align: center"
      >
        <el-button
          type="primary"
          @click="libraryTableclose"
        >关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import CRUD, {presenter, header, form, crud} from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import pagination from '@crud/Pagination'
import devDataExportTaskApi, {restart, suspend} from '@/api/dataTransfer/devDataTransfer/devDataExportTask'
import devDataExportListApi from '@/api/dataTransfer/devDataTransfer/devDataExportList'
import createTaskDialog from './createTaskDialog.vue'
import detailsDialog from './detailsDialog.vue'
import devAllDetailsDialog from './devAllDetailsDialog.vue'
import dataTransferFilterTable from '../dataTransferFilterTable'
import codemirror from '@/components/codemirror/codemirror.vue'

// crud交由presenter持有
const defaultCrud = CRUD({
  title: '',
  url: '/api/dev/data/export/task/page', crudMethod: {...devDataExportTaskApi}
})
const defaultForm = {}
export default {
  name: 'ScriptCheckResult',
  components: {rrOperation, pagination, createTaskDialog, detailsDialog, devAllDetailsDialog, dataTransferFilterTable, codemirror},
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
  data() {
    return {
      libraryTableName: '',
      ftpPercent: 0,
      ftpTakeUp: 0,
      takeUpUnit: null,
      ftpTotal: 0,
      lastRefreshTime: null,
      libraryTableNameFlag: false,
      createTaskDialogVisible: false,
      detailsDialogVisible: false,
      alldetailsDialogVisible: false,
      showFilterTableListVisible: false,
      crunTaskCode: null,
      tableList: [],
      taskStatusList: [
        {label: '未完成', value: 'incomplete'},
        {label: '已完成', value: 'complete'},
        {label: '暂停', value: 'suspend'}
      ],
      isDelDataFileStringList: [
        {label: '已删除', value: 'Y'},
        {label: '删除中', value: 'H'},
        {label: '未删除', value: 'N'}
      ],
      isFtpDeleting: false,
      isTaskDeleting: false,
      isRefreshing: false
    }
  },
  watch: {
    'crud.page.current': {
      handler: async function (val, oldVal) {
        const bodyWrapper = this.$refs.table.bodyWrapper
        bodyWrapper.scrollTop = 0
      }
    }
  },
  created() {
    this.initData()
  },
  methods: {
    async reset() {
      const response = await devDataExportTaskApi.findListByPage({size: this.crud.page.total})
      const ids = response.content.map(item => item.id)
      if (ids.length > 0) {
        await devDataExportTaskApi.reset(ids)
        this.$notify({title: '刷新成功', type: 'success'})
        this.crud.refresh()
      }
      this.countFtpTakeUp()
    },
    initData() {
      devDataExportTaskApi.countFtpTakeUp().then(res => {
        this.ftpTakeUp = res.takeUpSpace
        this.takeUpUnit = res.takeUpUnit
        this.ftpTotal = res.totalSpace
        this.ftpPercent = res.percentSpace
        this.lastRefreshTime = '上次刷新时间：' + res.lastRefreshTime
      })
    },
    countFtpTakeUp() {
      this.isRefreshing = true
      devDataExportTaskApi.countFtpTakeUp().then(res => {
        this.ftpTakeUp = res.takeUpSpace
        this.takeUpUnit = res.takeUpUnit
        this.ftpTotal = res.totalSpace
        this.ftpPercent = res.percentSpace
        this.lastRefreshTime = '上次刷新时间：' + res.lastRefreshTime
      }).finally(() => {
        this.isRefreshing = false
      })
    },
    customColor() {
      if (this.ftpPercent > 80) {
        return '#FF0000'
      } else if (this.ftpPercent > 60) {
        return '#e6a23c'
      } else {
        return '#67c23a'
      }
    },
    showFilterTableList() {
      this.showFilterTableListVisible = true
    },
    onClose() {
      this.createTaskDialogVisible = false
      this.crud.toQuery()
    },
    toShowDetail(taskCode) {
      this.detailsDialogVisible = true
      this.crunTaskCode = taskCode
    },
    toShowAllDetail() {
      this.alldetailsDialogVisible = true
    },
    continueRun(id) {
      this.$confirm(`确定要将该任务下的导出清单重新加载执行吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        devDataExportTaskApi.continueRunById(id).then(res => {
          loading.close()
          this.$notify({title: '成功', message: '操作成功！', type: 'success'})
          this.crud.toQuery()
        })
      }).catch(() => {
        loading.close()
      })
    },
    suspend(datas) {
      console.log(datas)
      console.log(this.getStatus(datas))
      this.$confirm(`确定要暂停选择的任务吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        devDataExportTaskApi.suspend(this.getIds(datas)).then(res => {
          loading.close()
          this.$notify({title: '成功', message: '暂停成功！', type: 'success'})
          this.crud.toQuery()
        })
      }).catch(() => {
        loading.close()
      })
    },
    abolish(datas) {
      this.$confirm(`确定要中止选择的任务吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        devDataExportTaskApi.abolish(this.getIds(datas)).then(res => {
          loading.close()
          this.$notify({title: '成功', message: '中止成功！', type: 'success'})
          this.crud.toQuery()
        })
      }).catch(() => {
        loading.close()
      })
    },
    restart(datas) {
      this.$confirm(`确定要重启选择的暂停任务吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        devDataExportTaskApi.restart(this.getIds(datas)).then(res => {
          loading.close()
          this.$notify({title: '成功', message: '重启成功！', type: 'success'})
          this.crud.toQuery()
        })
      }).catch(() => {
        loading.close()
      })
    },
    getIds(data) {
      const ids = []
      if (data instanceof Array) {
        data.forEach(val => {
          ids.push(val.id)
        })
      } else {
        ids.push(data.id)
      }
      return ids
    },
    getStatus(data) {
      const status = []
      if (data instanceof Array) {
        data.forEach(val => {
          status.push(val.taskStatus)
        })
      } else {
        status.push(data.taskStatus)
      }
      return status
    },
    getIsDel(data) {
      const status = []
      if (data instanceof Array) {
        data.forEach(val => {
          status.push(val.isDelDataFile)
        })
      } else {
        status.push(data.isDelDataFile)
      }
      return status
    },
    delFtpDataFile(id) {
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      this.$confirm(`确认删除该批次上的FTP数据文件吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        devDataExportTaskApi.delFileDataFile(id).then(res => {
          loading.close()
          this.$notify({
            title: '成功',
            message: '删除成功！',
            type: 'success'
          })
          this.crud.toQuery()
          this.countFtpTakeUp()
        })
      }).catch(() => {
        loading.close()
      })
    },
    batchDelFtpDataFile(datas) {
      this.$confirm(`确认删除该批次上的FTP数据文件吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.isFtpDeleting = true
        const ids = []
        if (datas instanceof Array) {
          datas.forEach(val => {
            ids.push(val.id)
          })
        } else {
          ids.push(datas.id)
        }
        devDataExportTaskApi.batchDelFileDataFile(ids).then(res => {
          this.$notify({
            title: '成功',
            message: '删除成功！',
            type: 'success'
          })
          this.crud.toQuery()
          this.countFtpTakeUp()
        }).finally(() => {
          this.isFtpDeleting = false
        })
      })
    },
    dynamicSuspendButton(datas) {
      const status = this.getStatus(datas)
      return !status.every(item => item === 'incomplete') || datas.length === 0
    },
    dynamicRestartButton(datas) {
      const status = this.getStatus(datas)
      return !status.every(item => item === 'suspend') || datas.length === 0
    },
    dynamicAbolishButton(datas) {
      const status = this.getStatus(datas)
      return !status.every(item => item === 'suspend' || item === 'incomplete') || datas.length === 0
    },
    dynamicBatchDelFileButton(datas) {
      const isDel = this.getIsDel(datas)
      return !isDel.every(item => item === 'N') || datas.length === 0
    },
    libraryTableopen(taskCode) {
      this.libraryTableNameFlag = true
      this.libraryTableName = ''
      const params = {
        taskCode: taskCode
      }
      devDataExportListApi.page(params).then(res => {
        const list = res.content
        for (let i = 0; i < list.length; i++) {
          this.libraryTableName += list[i].dbName + '.' + list[i].tableName + '\n'
        }
        console.log(this.libraryTableName)
      })
    },
    libraryTableclose() {
      this.libraryTableNameFlag = false
    },
    toDelete(datas) {
      // 未完成的不被删除
      const incompleteList = datas.filter(item => item.taskStatus === 'incomplete')
      // 已暂停的不被删除
      const suspendList = datas.filter(item => item.taskStatus === 'suspend')
      // 剩余的支持删除操作
      const filterDatas = datas.filter(itemA => !incompleteList.some(itemB => itemB.id === itemA.id) && !suspendList.some(itemC => itemC.id === itemA.id))
      const h = this.$createElement
      this.$confirm('提示', {
        title: '提示',
        message: h('div', [h('p', `选择【${datas.length}】条数据`), h('p', `存在【${incompleteList.length}】条未完成的不会被删除`), h('p', `存在【${suspendList.length}】条暂停的不会被删除`), h('p', `删除【${filterDatas.length}】条已选择数据？`)]),
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.isTaskDeleting = true
        // this.crud.delAllLoading = true
        this.crud.doDelete(filterDatas).finally(() => {
          this.isTaskDeleting = false
        })
      })
    }
  }
}
</script>
<style scoped lang="scss">
.no-wrap-progress{
  display: flex;
  align-items: center;

   ::v-deep .el-progress__text{
    white-space: nowrap;
  }
}
</style>
